package com.zrb.mobile;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.SearchCompanyAdapter;
import com.zrb.mobile.adapter.model.CompanyDtos;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

public class User_registercompany extends Activity implements OnClickListener {

	ImageView btnCompanyclear;

	AutoCompleteTextView editTextCompany;
	EditText editTextPwd;
	TextView mbtn_nextstep, mbtn_verifycode;
	Tip progTip;
	boolean isShow = false;
	// Toast��ʾ��
	private RelativeLayout notify_view;
	private TextView notify_view_text;
	ListView msearchlist;
	SearchCompanyAdapter companysAdapter;
	private EditText edit_company;
	Handler mhandler = new Handler();
	boolean isAuth = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.u_center_register_company);

		isAuth = this.getIntent().getBooleanExtra("isAuth", false);
		initView();
	}

	private void initView() {

		// Toast��ʾ��
		notify_view = (RelativeLayout) this.findViewById(R.id.notify_view);
		notify_view_text = (TextView) this.findViewById(R.id.notify_view_text);

		edit_company = (EditText) findViewById(R.id.edit_company);
		msearchlist = (ListView) this.findViewById(R.id.searchlist);
		msearchlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				msearchlist.setVisibility(View.GONE);
				if (companysAdapter != null) {
					edit_company.setText(companysAdapter.CurrentDatas.get(arg2).name);
				}
			}
		});

		btnCompanyclear = (ImageView) this.findViewById(R.id.company_btn_clean);
		editTextCompany = (AutoCompleteTextView) this
				.findViewById(R.id.edit_company);

		/*
		 * String[] games =
		 * this.getResources().getStringArray(R.array.games_array);
		 * ArrayAdapter<String> ada = new ArrayAdapter<String>(this,
		 * android.R.layout.simple_dropdown_item_1line , games);
		 */

		/*
		 * companysAdapter=new SearchCompanyAdapter(User_registercompany.this);
		 * for(int i=0;i<5;i++) companysAdapter.CurrentDatas.add(new
		 * QueryhistoryItem(i,"tests1"+i,1));
		 */

		// editTextCompany.setAdapter(companysAdapter);

		// editTextName.setOnFocusChangeListener(this);
		editTextCompany.addTextChangedListener(onNameTextChanged);

		mbtn_nextstep = (TextView) this.findViewById(R.id.btn_nextstep);
		// mbtn_nextstep.setEnabled(false);
		mbtn_nextstep.setOnClickListener(this);

		TextView txtTitle = (TextView) this.findViewById(R.id.txt_title);
		txtTitle.setText("��ҵ��֤");

		TextView rightHite = (TextView) this.findViewById(R.id.right_title);
		rightHite.setVisibility(isAuth ? View.GONE : View.VISIBLE);
		rightHite.setText("���");
		rightHite.setOnClickListener(this);

		View lefticon = this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
		// this.findViewById(R.id.button_register).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.btn_nextstep:
			user_register(true);
			break;
		case R.id.right_title:
			user_register(false);
			break;
		}
	}

	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "���ڱ�����...",
					true, true);
		else
			progTip.Show("���ڱ�����...");
	}

	private void user_register(boolean needCompany) {

		if (needCompany) {
			if (TextUtils.isEmpty(this.editTextCompany.getText().toString())) {
				initNotify("��ҵ��Ʋ�Ϊ��");
				return;
			}
		}
		showloading();
		String ServerUrl = "";

		RequestParams param = new RequestParams();
		if (!isAuth) {
			ServerUrl = "register/saveAppUser";
			/*
			 * param.put("mobile", AppSetting.curRegister.mobile);
			 * param.put("userType", AppSetting.curRegister.userType);
			 * param.put("smsCode", AppSetting.curRegister.smsCode);
			 * param.put("passWord", AppSetting.curRegister.passWord);
			 * param.put("uname", AppSetting.curRegister.uname);
			 */

		} else {
			ServerUrl = "user/updateAppUserInfo";
			param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
			// user/updateAppUserInfo?zrb_front_ut=306d8e1d90f87e7f55c075e959ede8c7&realname=����
		}

		if (needCompany)
			param.put("org", this.editTextCompany.getText().toString());

		CommonUtil
				.InfoLog("user_registercompany", ServerUrl + param.toString());
		ZrbRestClient.post(ServerUrl, param, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				progTip.Dismiss();
				initNotify(User_registercompany.this
						.getString(R.string.error_net_loadfail));
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				progTip.Dismiss();
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					RegisterDto tmpDto = gson.fromJson(results,
							RegisterDto.class);
					if (tmpDto.res == 1) {
						if (isAuth) {
							CommonUtil.showToast("�����ɹ�",
									User_registercompany.this);
							User_registercompany.this.finish();
							return;
						}
						/*Intent it = new Intent(User_registercompany.this, User_registerChoose.class);
						it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						it.putExtra("isfinish", true);
						startActivity(it);*/
					} else
						initNotify(tmpDto.msg);
				} catch (Exception e) {
					initNotify(User_registercompany.this
							.getString(R.string.error_serverdata_loadfail));
				}
			}
		});
	}

	private TextWatcher onNameTextChanged = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			String key = editTextCompany.getText() == null ? ""
					: editTextCompany.getText().toString().trim();
			if (key.length() >= 2) {
				// Log.i(��TAG , " key:"+key);
				/*
				 * List<Map<String , String>> lst =
				 * foursquared.getSelectStock(key);//��ݹؼ��ֲ�ѯ��Ʊ����
				 * StockListAdapter stockAdapter = new
				 * StockListAdapter(LoadableStockListActivity.this , lst);
				 */
				loadData(key);
			} else {
				msearchlist.setVisibility(View.GONE);
				// msearchlist.setAdapter(null);
			}

		}
	};

	private void loadData(String key) {

		RequestParams param = new RequestParams();
		param.put("companyName", key);

		// http://backend.zhaorongbao.com:8090/register/serchCompany?companyName=123
		ZrbRestClient.post("register/serchCompany", param,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						initNotify(User_registercompany.this
								.getString(R.string.error_net_loadfail));
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						// progTip.Dismiss();
						String results = new String(arg2);
						try {
							Gson gson = new Gson();
							CompanyDtos tmpDto = gson.fromJson(results,
									CompanyDtos.class);
							if (tmpDto.res == 1) {
								if (tmpDto.data == null
										|| tmpDto.data.size() == 0)
									return;
								if (companysAdapter == null) {
									companysAdapter = new SearchCompanyAdapter(
											User_registercompany.this);
									companysAdapter.setAll(tmpDto.data);
									msearchlist.setVisibility(View.VISIBLE);
									msearchlist.setAdapter(companysAdapter);
								} else {
									companysAdapter.setAll(tmpDto.data);
									companysAdapter.notifyDataSetChanged();
									msearchlist.setVisibility(View.VISIBLE);
								}
							}

						} catch (Exception e) {
							initNotify(User_registercompany.this
									.getString(R.string.error_serverdata_loadfail));
						}

					}
				});

	}

	/* ��ʼ��֪ͨ��Ŀ */
	private void initNotify(final String msg) {
		mhandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				notify_view_text.setText(msg);
				notify_view.setVisibility(View.VISIBLE);
				mhandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						notify_view.setVisibility(View.GONE);
					}
				}, 2000);
			}
		}, 1000);
	}

}
